import React, { Component } from 'react'
import App from "../../layout/App";
import './index.less';

// 引入公共组件
import Header from '../../components/Header/index.jsx';
import Operation from './components/Operation/index.jsx';
import TableList from './components/TableList/index.jsx';

// 引入公共方法
import { getTableList, saveTable } from './const';

import {
    vendorsDanger as danger,
    vendorsSuccess as success,
} from './../../utils/config.js';

let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if (cookieStr) {
    tenantId = cookieStr.split('=')[1];
}
// let tenantId = "x61tnmfx";
export default class BillsInquiry extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [], // 数据源
            editable: false, // 是否为编辑态
            isChecked: false, // 显示停用
            items: 1,       // 表格分页：总页数
            activePage: 1,   // 表格分页：当前页
            keyword: "", // 搜索内容
            deleteList: [], // 删除数组
        };
    }
    componentDidMount() {
        this.initPageData("");
    }

    initPageData = (value, alertText) => {
        // 数据初始化
        let params = {
            // pkTenant: tenantId,
            enableStatus: this.state.isChecked ? null : 1,
            keyword: value,
            ieStamp: new Date().getTime()
        }
        getTableList(params).then((res) => {
            let { resultCode, result, exMsg } = res.data;
            localStorage.setItem('originData', JSON.stringify(result)); // 存储元数据
            if (resultCode !== "busi_ex") {
                if(alertText) success({text: alertText}); // 提示两次，不是页面逻辑问题，而是组件问题，明天调查
                this.setState({ dataSource: result });
            } else {
                danger({ text: exMsg });
            }
        });
    }

    // 进入编辑
    changeTableEditStatus = () => {
        this.setState({ editable: true });
    }

    // 取消编辑
    cancelEdit = () => {
        this.setState({ editable: false }, () => {this.reloadData('', null)});
    }

    // 搜索
    searchTableList = ({ keyword }) => {
        this.setState({ keyword }, () => { this.initPageData(keyword) });

    }

    // 显示停用
    toggleChecked = (status) => {
        this.setState({ isChecked: status }, () => {
            this.initPageData(this.state.keyword);
        });
    }

    // 删除数组更新
    changeDeleteArr = (arr) => {
        this.setState({
            deleteList: [...arr]
        });
    }

    // 增行
    addItem = () => {
        let newItem = { code: "", name: "", enableStatus: 1, autoFocus: true };
        let copyDataSource = [...this.state.dataSource];
        copyDataSource.push(newItem);
        this.setState({ dataSource: copyDataSource, editable: true });
    }

    // 保存数据
    saveChange = () => {
        let saveData = [...this.state.dataSource];
        let notCanPostList = []; // 无法提交的数据
        saveData.forEach((item, index) => {
            // 只有code或者name的条目不能新增
            let isCanPostFlag = (item.code === "" && item.name != "") || (item.code != "" && item.name === "");
            if(isCanPostFlag) {
                notCanPostList.push({item, index});
            }
        });
        if(notCanPostList.length != 0) {
            let errorMsg = ""; // 报错信息
            notCanPostList.forEach(({item, index}) => {
                let keyName = item.code === "" ? "编码" : "里程碑名称";
                    errorMsg += `第${index+1}行${keyName}不能为空,请重新填写\n`;
            });
            danger({ text: errorMsg });
        } else {
            saveTable({vos: this.state.dataSource, deleteList: this.state.deleteList}).then((res) => {
                let { resultCode, result, exMsg } = res.data;
                if (resultCode !== "busi_ex") {
                    this.setState({dataSource: result, editable: false}, ()=> {success({text: '保存成功!'}), this.reloadData('', null)});
                } else {
                    danger({ text: exMsg });
                }
            });
        }
    }

    changeDataSource = (data, callback) => {
        this.setState({ dataSource: data }, () => {
            callback && callback();
        });
    }

    // 刷新数据
    reloadData = (value, alertText) => {
        this.initPageData(value, alertText);
    }

    render() {
        let { dataSource } = this.state;
        return (
            <App>
                <div className="main-container">
                    <Header
                        filename="计划"
                        divider="/"
                        title="里程碑" />
                    <Operation
                        searchValue={this.state.keyword}
                        activePage={this.state.activePage}
                        isChecked={this.state.isChecked}
                        editable={this.state.editable}
                        toggleChecked={this.toggleChecked}
                        searchTableList={this.searchTableList}
                        addItem={this.addItem}
                        saveChange={this.saveChange}
                        cancelEdit={this.cancelEdit}
                        reloadData={this.reloadData}
                        changeTableEditStatus={this.changeTableEditStatus}
                    />
                    <TableList
                        keyword={this.state.keyword}
                        items={this.state.items}
                        activePage={this.state.activePage}
                        changeTableEditStatus={this.changeTableEditStatus}
                        dataSource={dataSource}
                        changeDeleteArr={this.changeDeleteArr}
                        changeDataSource={this.changeDataSource}
                        refresh={this.reloadData}
                        editable={this.state.editable}></TableList>
                </div>
            </App>
        );
    }
}